package com.dailyblue.example.spring.boot.alipay.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dailyblue.example.spring.boot.alipay.bean.AlipayBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Value("${alipay.appId}")
    private String appId;
    @Value("${alipay.privateKey}")
    private String privateKey;
    @Value("${alipay.publicKey}")
    private String publicKey;
    @Value("${alipay.signType}")
    private String signType;
    @Value("${alipay.charset}")
    private String charset;
    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @GetMapping("/success")
    public String success() {
        return "Success";
    }

    @PostMapping
    public String alipay(AlipayBean alipay) throws AlipayApiException {
        // 生成alipay客户端
        AlipayClient client
                = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", charset, publicKey, signType);
        // 调用支付宝接口
        AlipayTradePagePayRequest alipayTradeAppPayRequest = new AlipayTradePagePayRequest();
        System.out.println("进入了这里：" + alipay);
        System.out.println("appId:" + appId);
        // 设置付款成功后应跳转的路径
        alipayTradeAppPayRequest.setNotifyUrl(notifyUrl);
        alipayTradeAppPayRequest.setReturnUrl(returnUrl);
        // 设置支付宝的各项参数
        String json = JSONArray.toJSONString(alipay);
        alipayTradeAppPayRequest.setBizContent(json);
        System.out.println("支付的参数是：" + json);
        System.out.println(JSONArray.toJSONString(alipayTradeAppPayRequest));
        // 生成最终的订单
        return client.pageExecute(alipayTradeAppPayRequest).getBody();
    }
}
